import os.path
import sys
import datetime

from PIL import Image

"""
功能：图片取模为TFT_eSPI库支持的565格式，生成图片对应的头文件
且不用设置tft.setSwapBytes(true)
"""


# Concatenate a byte sequence A,B,C,D to CDAB, P is a uint8_t pointer
# define DAT8TO32(P) ( (uint32_t)P[0]<<8 | P[1] | P[2]<<24 | P[3]<<16 )
def swap_byte(pixel):
    # 0x1234
    a = pixel[2]
    b = pixel[3]
    c = pixel[4]
    d = pixel[5]
    return "0x" + c + d + a + b


print("swapByte=", swap_byte("0x1234"))


def rgb565(r, g, b):
    # 像素rgb数据转换为rgb565格式
    rgb565 = (r & 0b11111000) << 8
    rgb565 = rgb565 | ((g & 0b11111100) << 3)
    rgb565 = rgb565 | ((b & 0b11111000) >> 3)
    # 格式化为0xFFFF格式字符串
    return f"0x{rgb565:04X}"


def convert(img):
    hex = ""
    for y in range(img.height):
        for x in range(img.width):
            pixel = img.getpixel((x, y))
            # print("x=%d,y=%d,pixel=%s" % (x, y, pixel))
            r = pixel[0]
            g = pixel[1]
            b = pixel[2]
            # imgNew.putpixel((x, y), (r & 0b11111000, g & 0b11111100, b & 0b11111000))
            s = rgb565(r, g, b)
            s = swap_byte(s)
            hex += s + ","
        hex += "\n"

    hex = hex.rstrip("\n,")
    # print(hex)
    return hex


def write_c_header_file(file_name, img, hex):
    name = os.path.splitext(file_name)[0]
    now = datetime.datetime.now()
    time = now.strftime("%Y-%m-%d %H:%M:%S")
    with open(f"{name}.h", "w") as f:
        f.writelines("// Generated by  : Convert565 v1.0\n")
        f.writelines("// Generated from: {}\n".format(file_name))
        f.writelines("// Time generated: {}\n".format(time))
        f.writelines("// Dimensions    : {}x{} pixels\n".format(img.width, img.height))
        f.writelines("// Size          : {} Bytes\n".format(img.width * img.height * 2))
        f.writelines("\n")
        f.writelines("#include <pgmspace.h>\n")
        f.writelines("\n")
        f.writelines("const uint16_t img{}[{}] PROGMEM ={{\n".format(name, img.width * img.height))
        f.write(hex)
        f.writelines("\n")
        f.writelines("};\n")


# 测试
# img = Image.open("test/fengjing.jpeg")
# imgRGB = img.convert('RGB')
# hex = convert(imgRGB)
# generateHeaderFile("fengjing.jpeg", imgRGB, hex)

if __name__ == '__main__':
    print(sys.argv)
    if len(sys.argv) < 2:
        print("用法: 把要转换的 JPG/PNG/BMP 文件拖到.exe图标上即可")
        exit(0)

    for i, img_path in enumerate(sys.argv[1:]):
        fileName = os.path.basename(img_path)
        print("正在转换图片[{}] ...".format(fileName))
        img = Image.open(img_path)
        imgRGB = img.convert('RGB')
        hex = convert(imgRGB)
        write_c_header_file(fileName, imgRGB, hex)
